<template>
  <div class="notification-center">
    <!-- 通知触发器 -->
    <div class="notification-trigger" @click="toggleNotifications">
      <el-badge :value="unreadCount" :max="99" class="notification-badge">
        <el-button type="text" size="small" class="notification-btn">
          <el-icon><el-icon-Bell /></el-icon>
        </el-button>
      </el-badge>
      
      <!-- 通知面板 -->
      <transition name="notification-fade">
        <div v-if="showNotifications" class="notification-panel" @click.stop>
          <div class="panel-header">
            <h3 class="panel-title">通知中心</h3>
            <div class="panel-actions">
              <el-button type="text" size="small" @click="markAllAsRead" v-if="unreadCount > 0">
                全部已读
              </el-button>
              <el-button type="text" size="small" @click="clearAllNotifications">
                清空
              </el-button>
            </div>
          </div>
          
          <!-- 通知列表 -->
          <div class="notification-list" v-if="notifications.length > 0">
            <div 
              v-for="notification in notifications" 
              :key="notification.id" 
              class="notification-item"
              :class="{ 'unread': !notification.read, 'expired': notification.type === 'expired' }"
              @click="markAsRead(notification.id)"
            >
              <div class="notification-icon" :class="notification.type">
                <el-icon :size="20"><component :is="getNotificationIcon(notification.type)" /></el-icon>
              </div>
              <div class="notification-content">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-message">{{ notification.message }}</div>
                <div class="notification-meta">
                  <span class="notification-time">{{ getRelativeTime(notification.timestamp) }}</span>
                  <span v-if="notification.type === 'vulnerability'" class="risk-level" :class="notification.riskLevel">
                    {{ getRiskLevelText(notification.riskLevel) }}
                  </span>
                </div>
              </div>
              <div class="notification-actions">
                <el-button 
                  type="text" 
                  size="small" 
                  @click.stop="handleNotificationAction(notification)"
                  v-if="notification.actionButton"
                >
                  {{ notification.actionButton }}
                </el-button>
                <el-button 
                  type="text" 
                  size="small" 
                  icon="el-icon-Close" 
                  @click.stop="removeNotification(notification.id)"
                />
              </div>
            </div>
          </div>
          
          <!-- 空状态 -->
          <div v-else class="empty-notifications">
            <el-icon class="empty-icon"><el-icon-Bell /></el-icon>
            <p class="empty-text">暂无通知</p>
          </div>
          
          <!-- 底部导航 -->
          <div class="panel-footer" v-if="notifications.length > 0">
            <el-tabs v-model="activeTab" class="notification-tabs">
              <el-tab-pane label="全部" name="all"></el-tab-pane>
              <el-tab-pane label="未读" name="unread"></el-tab-pane>
              <el-tab-pane label="安全警报" name="vulnerability"></el-tab-pane>
              <el-tab-pane label="系统通知" name="system"></el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </transition>
    </div>
    
    <!-- 通知遮罩 -->
    <transition name="fade">
      <div v-if="showNotifications" class="notification-overlay" @click="closeNotifications"></div>
    </transition>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'NotificationCenter',
  emits: ['notification-click', 'action-click'],
  setup(props, { emit }) {
    const showNotifications = ref(false)
    const activeTab = ref('all')
    const notifications = ref([])
    let pollingInterval = null

    // 初始化通知数据
    const initNotifications = () => {
      notifications.value = [
        {
          id: 1,
          type: 'vulnerability',
          title: '发现高危漏洞',
          message: '在服务器 web-server-01 上发现 CVE-2023-4567 高危漏洞',
          timestamp: new Date(Date.now() - 30 * 60 * 1000), // 30分钟前
          read: false,
          riskLevel: 'high',
          actionButton: '立即修复'
        },
        {
          id: 2,
          type: 'system',
          title: '扫描任务完成',
          message: '目标 example.com 的深度扫描已完成，发现 5 个漏洞',
          timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000), // 2小时前
          read: true
        },
        {
          id: 3,
          type: 'warning',
          title: '扫描器资源不足',
          message: '扫描器 Scanner-3 资源使用率超过 85%，可能影响扫描性能',
          timestamp: new Date(Date.now() - 5 * 60 * 60 * 1000), // 5小时前
          read: false
        },
        {
          id: 4,
          type: 'success',
          title: '漏洞修复成功',
          message: '服务器 db-server-02 上的 CVE-2023-1234 漏洞修复成功',
          timestamp: new Date(Date.now() - 24 * 60 * 60 * 1000), // 1天前
          read: true
        },
        {
          id: 5,
          type: 'expired',
          title: '扫描任务超时',
          message: '目标 test.org 的扫描任务因超时而终止',
          timestamp: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000), // 2天前
          read: true
        }
      ]
    }

    // 计算未读通知数量
    const unreadCount = computed(() => {
      return notifications.value.filter(notification => !notification.read).length
    })

    // 获取相对时间
    const getRelativeTime = (date) => {
      if (!date) return ''
      const now = new Date()
      const diffMs = now - new Date(date)
      const diffSecs = Math.floor(diffMs / 1000)
      const diffMins = Math.floor(diffSecs / 60)
      const diffHours = Math.floor(diffMins / 60)
      const diffDays = Math.floor(diffHours / 24)
      
      if (diffSecs < 60) return `${diffSecs}秒前`
      if (diffMins < 60) return `${diffMins}分钟前`
      if (diffHours < 24) return `${diffHours}小时前`
      if (diffDays < 30) return `${diffDays}天前`
      return new Date(date).toLocaleDateString()
    }

    // 获取通知图标
    const getNotificationIcon = (type) => {
      const iconMap = {
        vulnerability: 'el-icon-WarningFilled',
        system: 'el-icon-InfoFilled',
        warning: 'el-icon-ExclamationFilled',
        success: 'el-icon-SuccessFilled',
        expired: 'el-icon-CloseFilled'
      }
      return iconMap[type] || 'el-icon-BellFilled'
    }

    // 获取风险等级文本
    const getRiskLevelText = (level) => {
      const levelMap = {
        high: '高危',
        medium: '中危',
        low: '低危'
      }
      return levelMap[level] || '未知'
    }

    // 切换通知面板显示
    const toggleNotifications = () => {
      showNotifications.value = !showNotifications.value
      if (showNotifications.value && activeTab.value === 'unread' && unreadCount.value === 0) {
        activeTab.value = 'all'
      }
    }

    // 关闭通知面板
    const closeNotifications = () => {
      showNotifications.value = false
    }

    // 标记为已读
    const markAsRead = (notificationId) => {
      const notification = notifications.value.find(n => n.id === notificationId)
      if (notification && !notification.read) {
        notification.read = true
        emit('notification-click', notification)
      }
    }

    // 标记全部已读
    const markAllAsRead = () => {
      notifications.value.forEach(notification => {
        notification.read = true
      })
      ElMessage.success('已将所有通知标记为已读')
    }

    // 移除通知
    const removeNotification = (notificationId) => {
      const index = notifications.value.findIndex(n => n.id === notificationId)
      if (index > -1) {
        notifications.value.splice(index, 1)
      }
    }

    // 清空所有通知
    const clearAllNotifications = () => {
      ElMessageBox.confirm(
        '确定要清空所有通知吗？此操作不可恢复。',
        '确认清空',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        notifications.value = []
        ElMessage.success('所有通知已清空')
      }).catch(() => {})
    }

    // 处理通知操作
    const handleNotificationAction = (notification) => {
      emit('action-click', notification)
      // 根据通知类型执行不同操作
      if (notification.type === 'vulnerability') {
        ElMessage.info('正在跳转到漏洞修复页面...')
        // 这里可以添加跳转逻辑
      }
    }

    // 过滤通知
    const filteredNotifications = computed(() => {
      if (activeTab.value === 'all') {
        return notifications.value
      } else if (activeTab.value === 'unread') {
        return notifications.value.filter(n => !n.read)
      } else {
        return notifications.value.filter(n => n.type === activeTab.value)
      }
    })

    // 开始轮询新通知
    const startPolling = () => {
      pollingInterval = setInterval(() => {
        // 模拟轮询新通知
        console.log('Checking for new notifications...')
        // 实际项目中应该调用API获取新通知
      }, 30000) // 每30秒检查一次
    }

    // 停止轮询
    const stopPolling = () => {
      if (pollingInterval) {
        clearInterval(pollingInterval)
      }
    }

    // 添加新通知的方法（可从父组件调用）
    const addNotification = (notification) => {
      const newNotification = {
        id: Date.now(),
        timestamp: new Date(),
        read: false,
        ...notification
      }
      notifications.value.unshift(newNotification)
    }

    // 监听点击外部关闭
    const handleClickOutside = (event) => {
      const notificationCenter = event.target.closest('.notification-center')
      if (!notificationCenter && showNotifications.value) {
        closeNotifications()
      }
    }

    onMounted(() => {
      initNotifications()
      startPolling()
      document.addEventListener('click', handleClickOutside)
    })

    onUnmounted(() => {
      stopPolling()
      document.removeEventListener('click', handleClickOutside)
    })

    return {
      showNotifications,
      activeTab,
      notifications,
      unreadCount,
      filteredNotifications,
      toggleNotifications,
      closeNotifications,
      markAsRead,
      markAllAsRead,
      removeNotification,
      clearAllNotifications,
      handleNotificationAction,
      getRelativeTime,
      getNotificationIcon,
      getRiskLevelText,
      // 暴露给父组件的方法
      addNotification
    }
  }
}
</script>

<style scoped>
.notification-center {
  position: relative;
  z-index: 1000;
}

.notification-badge {
  --el-badge-fill: #ff4d4f;
  --el-badge-text-color: #ffffff;
}

.notification-panel {
  position: absolute;
  top: 100%;
  right: 0;
  width: 400px;
  max-height: 500px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  margin-top: 8px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 暗色模式支持 */
:global(.dark-mode) .notification-panel {
  background: #1f2937;
  color: #f3f4f6;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

:global(.dark-mode) .panel-header {
  border-bottom-color: rgba(255, 255, 255, 0.1);
}

.panel-title {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
  color: #1f2937;
}

:global(.dark-mode) .panel-title {
  color: #f3f4f6;
}

.panel-actions {
  display: flex;
  gap: 8px;
}

.notification-list {
  flex: 1;
  overflow-y: auto;
  max-height: 360px;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: all 0.2s ease;
}

:global(.dark-mode) .notification-item {
  border-bottom-color: rgba(255, 255, 255, 0.05);
}

.notification-item:hover {
  background: #f8fafc;
}

:global(.dark-mode) .notification-item:hover {
  background: #374151;
}

.notification-item.unread {
  background: #e6f7ff;
}

:global(.dark-mode) .notification-item.unread {
  background: rgba(59, 130, 246, 0.1);
}

.notification-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.notification-icon.vulnerability {
  background: #fee2e2;
  color: #ef4444;
}

.notification-icon.system {
  background: #dbeafe;
  color: #3b82f6;
}

.notification-icon.warning {
  background: #fef9c3;
  color: #f59e0b;
}

.notification-icon.success {
  background: #dcfce7;
  color: #22c55e;
}

.notification-icon.expired {
  background: #f3f4f6;
  color: #6b7280;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-title {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

:global(.dark-mode) .notification-title {
  color: #f3f4f6;
}

.notification-message {
  font-size: 13px;
  color: #6b7280;
  margin-bottom: 6px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

:global(.dark-mode) .notification-message {
  color: #9ca3af;
}

.notification-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.notification-time {
  font-size: 11px;
  color: #9ca3af;
}

.risk-level {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
  font-weight: 500;
}

.risk-level.high {
  background: #fee2e2;
  color: #ef4444;
}

.risk-level.medium {
  background: #fef9c3;
  color: #f59e0b;
}

.risk-level.low {
  background: #dcfce7;
  color: #22c55e;
}

.notification-actions {
  display: flex;
  align-items: center;
  gap: 4px;
}

.empty-notifications {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #9ca3af;
}

.empty-icon {
  font-size: 32px;
  margin-bottom: 12px;
  opacity: 0.5;
}

.empty-text {
  font-size: 14px;
  margin: 0;
}

.panel-footer {
  border-top: 1px solid #f0f0f0;
}

:global(.dark-mode) .panel-footer {
  border-top-color: rgba(255, 255, 255, 0.1);
}

.notification-tabs {
  --el-tabs-header-height: 48px;
}

/* 过渡动画 */
.notification-fade-enter-active,
.notification-fade-leave-active {
  transition: all 0.3s ease;
}

.notification-fade-enter-from,
.notification-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.notification-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .notification-panel {
    width: calc(100vw - 32px);
    max-width: 400px;
    left: 50%;
    right: auto;
    transform: translateX(-50%);
  }
}
</style>